<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>产品新增</title>
<link rel="stylesheet" href="../../css/ecp.min.css" />
<!-- <link rel="stylesheet" href="../../css/picUpload.css" /> -->
<link rel="stylesheet" href="../../js/webuploader/webuploader.css" />
<script src="../../js/lib.min.js"></script>
<script src="../../js/requirejsConfigObj.js"></script>
<script src="../../js/requirejs/2.1.17.js"></script>
<script src="../../js/datepicker/4.8.b2/WdatePicker.js"></script>
<script src="../../js/common.min.js"></script>

<style  type="text/css">
    .check_error{color:red;border-color:red;}
    .width130{width:460px;height: 25px;}
    .errText{margin-left:10px;visibility:hidden; }
   
</style>    
</head>
<body> 
  <div id="showMsg" class="project"></div> 
  <div class="project-dialog"> 
   <form id="formItem" name="formItem" style="width: 100%;"> 
     <div>
      <table class="form_table" width="95%"> 
       <tbody id="table_tbody">
       <tr>
            <td width="130">
                 <label class="description"> <span class="fn-high">*</span>产品名称</label>
            </td>
            <td width="260" colspan="3">
                <input type="text" class="inputWidth width130" maxlength="100" name="productNm" id="productNm"/>                   
            </td>            
       </tr>
       <tr>
            <td width="130">
                 <label class="description"> <span class="fn-high">*</span>产品类型</label>
            </td>
            <td width="260">
                <select class="inputSelect inputWidth" id="productTypeCd" name="productTypeCd">
					<option value="">--请选择--</option>
					<option value="1001">禅美</option>
					<option value="1002">禅修</option>
					<option value="1003">其他</option>
				 </select>                  
            </td>            
       </tr>         
        <tr>
            <td>
                 <label class="description"> 产品照片</label>
            </td>
            <td>
                <div class="row cl">
					<input type='hidden' id='filepath'>
                    <div class="uploader-thum-container">
                    	<input type=file id=browsefile style="visibility:hidden;" onchange="imgFileOpt();"/>
						<div id="fileList" class="" style="height:auto;margin-bottom:20px;"></div>
						<div class="normalBtnArea" style="clear: both;">
							<a class="normalBtn BGblue largeBtn" href="javascript:;" id="" style="padding: 12px 20px;" onclick="browsefile.click();">选择图片</a> 
						</div>
                	</div>
                	<p style="margin-top:10px;">照片类型支持：JPEG、PNG、JPG、Gif格式的图片,照片小于2M</p>
				</div>     
            </td>
        </tr>        
        <tr>
           <td>
               <label class="description"> <span class="fn-high">*</span>产品简介</label>
           </td>
           <td colspan="3">
               <textarea type="text" name="productDesc" id="productDesc" class="form-textarea"  placeholder="请输入2000字以内" style="width: 700px;height: 130px;" resize:none ;onblur="true" maxlength="500"></textarea>
           </td>
       </tr>
       <tr>
	        <td>
	            <label class="description"> <span class="fn-high">*</span>产品介绍</label>
	        </td>
	        <td>
	            <textarea type="text" name="productCntt" id=productCntt style="width:650px;height:400px;visibility:hidden;"></textarea>
	        </td>
       </tr>       
       </tbody> 
      </table> 
      <hr />
     <div class="formBtnArea"> 
      <table width="100%"> 
       <tbody>
        <tr> 
         <td> 
          <div class="normalBtnArea fn-center"> 
           <input type="hidden" id="hideDataRoute" name="hideDataRoute" value=""/>
           <a class="normalBtn BGblue largeBtn" href="javascript:;" id="J_save" onclick="save()">保存</a> 
           <a href="javascript:;" class="BGblue largeBtn" id="J_cancel" onclick="cancleConfirm()"><span>返回</span></a> 
          </div> 
          </td> 
        </tr> 
       </tbody>
      </table> 
     </div> 
    </div> 
   </form> 
  </div>
 </body>

<script src="../../js/kindeditor/kindeditor.js"></script>
<script src="../../js/webuploader/webuploader.js"></script>
<script src="../../js/self_fun.js"></script>
<script type="text/javascript">

$(function(){
	//qryOpAndRaVal();
	editor = KindEditor.create('textarea[name="productCntt"]', {
        allowFileManager: true,
        uploadJson: "../../front/sh/care!uploadPicImg?uid=p002&type=rich",
        items: [
          'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
          'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
          'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
          'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
          'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
          'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
          'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
          'anchor', 'link', 'unlink', '|', 'about'
        ]
      });
	//initWeb("#fileList","#filePicker",'#filePaths');
});
function  qryOpAndRaVal(){
    var str = "5000$5023";
    var param={queryType:str};
    Util.ajax.postJsonSync("/home", param, function(json,status){
              alert(json.aaaa);           
    });
}
function save(){  
	var productNm = $("#productNm").val();
   	if(isDataNull(productNm)){
   		top.Util.dialog.tips('请填写产品名称！');
   	 return;
   	}
   	var productDesc = $("#productDesc").val();
   	if(isDataNull(productDesc)){
   		top.Util.dialog.tips('请填写产品简介！');
   	 return;
   	}
   	var productTypeCd = $("#productTypeCd").val();
   	if(isDataNull(productTypeCd)){
   		top.Util.dialog.tips('请选择产品类型！');
   	 return;
   	}
	var ntcCnttContent = "";
   	ntcCnttContent = editor.html();
   	if(ntcCnttContent=='' ||ntcCnttContent==null){
    	 top.Util.dialog.tips('请填写产品介绍！');
    	 return;
    } 
	var filepath = $("#filepath").val(); 	
   	var param = {
   			'productNm':productNm,
   			'productDesc':productDesc,
   			'productTypeCd':productTypeCd,
   			'productCntt':ntcCnttContent,
   			'picHeadFile':filepath,
   	}
	Util.ajax.postJsonSync("/addProductInfo",param,function(json,status){
           if(status){
        	   if(json.bean.rtnCd == "00"){ 
                   window.parent.inint();
                   window.parent.closeIframeDialog();
               }else{              
                   window.parent.setTip("保存失败",top,2000);
               }
           }else{
               Util.dialog.tips("保存失败,请重试!!");
           }
     }); 
}
	//取消确认弹框
	function cancleConfirm(){
		window.parent.closeIframeDialog();
	};
		
  
    //表单校验
    var validatePoorHouseInfo = $("#formItem").validate({
    	rules:{
    		productNm:{
        		required:true,
        	},
        	productTypeCd:{
        		required:true,
        	},
        	productDesc:{
        		required:true,
            }
        },
        messages:{
        	productNm:{
        		required:"必填",
            },
            productTypeCd:{
            	required:"必填",
            },
            productDesc:{
            	required:"必填",
            }
        },
        showErrors:function(){
            this.defaultShowErrors();
        }
    });
    
 
  //图片上传
    function initWeb(fileId,pickerId,picPaths){
  	  var $ = jQuery,
       $list = $(fileId),
  	// 优化retina, 在retina下这个值是2
  	      ratio = window.devicePixelRatio || 1,
  	
  	// 缩略图大小
  	      thumbnailWidth = 100 * ratio,
  	      thumbnailHeight = 100 * ratio,
  	// Web Uploader实例
  	 uploader;
  	 var familyPicUrls = '';
  	 var allPicUrls = '';//包含所有前端页面预览过的图片的地址
  	// 初始化Web Uploader
  	uploader = WebUploader.create({
  	  // 自动上传。
  	  auto: true,
  	
  	  // 图片上传前进行压缩
  	  compress: false,
  	  duplicate :true,  
  	  // swf文件路径
  	  swf:  '../../js/webuploader/Uploader.swf',
  	  //server:'../../front/sh/info!fanxianUploadPicImg?uid=s001',
  	  server:'/uploadPicFile',
  	  // 选择文件的按钮。可选。
  	  // 内部根据当前运行是创建，可能是input元素，也可能是flash.
  	  pick: {id:pickerId,multiple:true},
  	  // 只允许选择文件，可选。
  	  accept: {
  	      title: 'Images',
  	      extensions: 'gif,jpg,jpeg,bmp,png',
  	      mimeTypes: 'image/jpg,image/jpeg,image/png,image/bmp,image/gif'
  	  },
  	   fileVal: "uploadfile",
  	   fileSingleSizeLimit:3145728
  	});
  	
  	         
  	//图片加入队列前,判断图片大小
  	uploader.on('beforeFileQueued',function(file){
  	    var picUpload = $(fileId).find(".file-item");
  	    if(picUpload.length >= 10){
  	      Util.dialog.tips("最多只能上传10张照片",top,1000);
  	      return false;
  	    }  
  	    if(file.size > 3145728){
  	        Util.dialog.tips("图片大于3M，请重新选择",top,1000);
  	    }
  	    var injStra = ["script", "mid", "master", "truncate ", "insert ", "select ",
                         "delete ", "update ", "declare", "iframe", "onreadystatechange", "alert", "atestu", "xss",
                         ";","'","\"","<",">","(",")",",","\\","svg","confirm","prompt","onload","onmouseover",
                         "onfocus","onerror","and ","or ","union ","where ","limit ","group ","by ","hex","substr",
                         "\r","\n"];
          var injFileName = file.name.toLowerCase();
          var flag = 1;
          for (var i = 0; i<injStra.length; i++) {
              if (injFileName.indexOf(injStra[i])>=0) {              
                  flag =2;
              }
          }
          if(flag == 2){
              Util.dialog.tips("图片名称含有特殊字符，请修改");                
              return false;
          }
  	    
  	})
  	uploader.on( 'uploadStart', function( file ) {});
  	// 当有文件添加进来的时候
  	uploader.on( 'fileQueued', function( file ) {  
  	  var $li = $(
  	          '<div id="' + file.id + '" class="file-item thumbnail">' +
  	          '<img>' +
  	          '<div class="delpic"><span id=""  style="color: #08c;visibility:hidden;" onclick="delPic(this)">删除图片</span></div><div class="excelProcess" style="visibility:hidden;"></div></div>'
  	  ),
  	  $img = $li.find('img');
  	  $list.append( $li ); 
  	$(".delpic").find('span').on('click',function(){	    
  		var _this=$(this);
  	      var picId=_this.attr("id");//在图片上传时已修改为图片地址
  	      var picUrls = $(picPaths).val();  
  	      var regx = new RegExp('\\,?'+picId);
  	      var path = picUrls.replace(regx, "");
  	      if(path.indexOf(',') === 0){path = path.substring(1);}
  	      $(picPaths).val(path);
  	      _this.parents(".file-item").remove();
  	});
  	// 创建缩略图
  	uploader.makeThumb( file, function( error, src ) {
  	  if ( error ) {
  	      $img.replaceWith('<span>不能预览</span>');
  	      return;
  	  }   
  	  $img.attr( 'src', src );
  	}, 60, 60 );	
  	});
  	
  	// 文件上传过程中创建进度条实时显示。
  	uploader.on( 'uploadProgress', function( file, percentage ) {
  	  $('#'+file.id).find('.excelProcess').css('visibility','visible');
  	  $('#'+file.id).find('.excelProcess').html('<p class="progress" style="width:'+percentage * 99+'%"></p><span>'+(percentage.toFixed(2)* 99)+'%</span>');
  	});
  	// 文件上传成功，给item添加成功class, 用样式标记上传成功。
  	uploader.on( 'uploadSuccess', function(file, data) {
  	  var picUrl = data.picUrl;
  	  var imgName = data.fileName;
  	  familyPicUrls = $(picPaths).val();
  	  familyPicUrls += ","+picUrl;
  	  if(familyPicUrls.indexOf(',') === 0){familyPicUrls = familyPicUrls.substring(1);}
  	  $('#' + file.id).find(".delpic span").attr("id", picUrl);
  	  $(picPaths).val(familyPicUrls);//最终上传图片
  	  $( '#'+file.id ).addClass('upload-state-done');
  	  $('#'+file.id).find('.excelProcess').css('visibility','visible');
  	  if(isDataNull(picUrl)){
  		  $('#'+file.id).find('.excelProcess').html('上传失败');
  	  }else{
  	 	 $('#'+file.id).find('.excelProcess').html('上传成功');
  	  }
  	  $('#'+file.id).find(".delpic span").css('visibility','visible');
  	});
  	// 文件上传失败，显示上传出错。
  	uploader.on( 'uploadError', function( file ) {
  	  var $li = $( '#'+file.id ),
  	          $error = $li.find('div.error');
  	  if ( !$error.length ) {
  	      $error = $('<div class="error"></div>').appendTo( $li );
  	  }
  	  if(uploader.getFiles('queued','progress').length == 0){
  		  $("J_save").css('visibility','visible');
  	  }
  	  $("#"+file.id).remove();
  	});
  	
  	// 完成上传完了，成功或者失败，先删除进度条。
  	uploader.on( 'uploadComplete', function( file ) {
  	
  	});
  	
  	//解决ie9下上传png无法到后台的问题
  	if(navigator.userAgent.indexOf("MSIE")>0 && navigator.userAgent.indexOf("MSIE 9.0")>0){   
  	var setHeader = function(object, data, headers) {
  	      headers['Access-Control-Allow-Origin'] = '*';
  	      headers['Access-Control-Request-Headers'] = 'content-type';
  	      headers['Access-Control-Request-Method'] = 'POST';
  	  }
  	uploader.on('uploadBeforeSend ', setHeader);
  	}
    }
    function delPic(_this){
  	    var picId=$(_this).attr("id");//在图片上传时已修改为图片地址
  	    var picUrls = $(filePaths).val();  
  	    var regx = new RegExp('\\,?'+picId);
  	    var path = picUrls.replace(regx, "");
  	    if(path.indexOf(',') === 0){path = path.substring(1);}
  	    $(filePaths).val(path);
  	    $(_this).parents(".file-item").remove();
    } 
    function imgFileOpt(){
    	var reader = new FileReader();
        var AllowImgFileSize = 2100000; //上传图片最大值(单位字节)（ 2 M = 2097152 B ）超过2M上传失败
        var file = $("#browsefile")[0].files[0];
        var imgUrlBase64;
        if (file) {
            //将文件以Data URL形式读入页面  
            imgUrlBase64 = reader.readAsDataURL(file);
            reader.onload = function (e) {
              //var ImgFileSize = reader.result.substring(reader.result.indexOf(",") + 1).length;//截取base64码部分（可选可不选，需要与后台沟通）
              if (AllowImgFileSize != 0 && AllowImgFileSize < reader.result.length) {
            	  top.Util.dialog.tips( '上传失败，请上传不大于2M的图片！');
                    return;
                }else{
                    //执行上传操作
                    html = '<img src="'+reader.result+'" width="200" height="200"/>';
                    $("#fileList").html(html);
                    $("#filepath").val(reader.result);
                    setHeight();
                }
            }
         }         
    }
    function setHeight(){
        window.parent.setIframeHeight();
    }
</script>
</body>
</html>